package com.lxit.video.controller;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.lxit.video.bean.UserInfo;
import com.lxit.video.service.UserService;
import com.lxit.video.service.impl.UserServiceImpl;
import com.lxit.video.util.LayuiPageUtil;
import com.lxit.video.util.PageUtil;

@Controller
@RequestMapping(value = "/user/")
public class UserController {

	@Autowired
	private UserService userServiceImpl;

	@RequestMapping(value = "add")
	public String userAdd(UserInfo u,Map<String,Object>map) {
		u.setuTypeId(1);
		u.setUserStatus(0);
		Date date = new Date();
		long times = date.getTime();// 时间戳
		Date date1 = new Date(times);
		u.setCreateTime(date1);
		int nameCount = userServiceImpl.nameCount(u.getUserAlias());
		int phoneCount = userServiceImpl.phoneCount(u.getUserPhone());
		if (nameCount == 0 && phoneCount == 0) {
			boolean result = userServiceImpl.saveUser(u);
			if (result == false) {
				map.put("userInfo",u.getUserPhone());
				return "redirect:../page/login.html";
			} else {
				return "redirect:../page/register.html";
			}
		} else {
			return "redirect:../page/register.html";
		}

	}

	@RequestMapping(value = "login")
	public String login(String userPhone, String password, HttpSession session) {
		List<UserInfo> list = userServiceImpl.login(userPhone, password);
		session.setAttribute("user", list);
		if (list.size() > 0) {
			return "redirect:../page/index.html";
		} else {
			return "redirect:../page/login.html";
		}

	}

	@RequestMapping(value = "adminLogin")
	public String admin_login(String userPhone, String password, HttpSession session) {
		List<UserInfo> list = userServiceImpl.admin_login(userPhone, password);
		session.setAttribute("adminUser", list);
		if (list.size() > 0) {
			return "redirect:../X-admin/index.html";
		} else {
			return "redirect:../X-admin/login.html";
		}
	}

	@ResponseBody
	@RequestMapping(value="aaa")
	public Object userPage(@RequestParam(value = "page") Integer pageIndex,
			@RequestParam(value = "limit") Integer pageSize, String userAlias) {
		PageUtil<UserInfo> pageUtil = userServiceImpl.pageGetAll(pageIndex, pageSize, userAlias);
		Object json = null;
		if(pageUtil!=null) {
			LayuiPageUtil<UserInfo> layuiPageUtil = new LayuiPageUtil<>(pageUtil.getTotal(), pageUtil.getRows());
			json = JSONObject.toJSON(layuiPageUtil);
		}
		return json;
	}
}